package com.javen.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Javen
 *
 * NEW
 * RUNNABLE
 * BLOCKED
 * WAITING
 * TIMED_WAITING
 * TERMINATED
 */
@Slf4j
public class ThreadPoolDemo {
    public static void threadPool() {
        //        ExecutorService threadPool = Executors.newFixedThreadPool(5); // 固定线程的线程池
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();// 单个线程的线程池
//        ExecutorService threadPool = Executors.newCachedThreadPool(); // 可变线程的线程池
        log.info("CPU 核数:{}", Runtime.getRuntime().availableProcessors());
        // 如果是 CPU 密集型：CPU 核数 + 1 个线程池
        // IO 密集型：1、CPU 核数 * 2      2、 CPU 核数 / (1-堵塞系数（0.8~0.9）)   比如8核 CPU： 8 /(1-0.9) = 80 线程数
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                1L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                // 直接抛出 RejectedExecutionException 异常
//                new ThreadPoolExecutor.AbortPolicy()
                // 调用者协调，谁调用就回退给谁
//                new ThreadPoolExecutor.CallerRunsPolicy()
                // 抛弃等待时间久的
//                new ThreadPoolExecutor.DiscardOldestPolicy()
                // 直接抛弃
                new ThreadPoolExecutor.DiscardPolicy()
        );


        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> log.info("{} 执行....", Thread.currentThread().getName()));
            }
        } finally {
            threadPool.shutdown();
        }
    }

    public static void main(String[] args) {
      threadPool();
    }
}


